package com.gooznt.wrapperProp;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;

public class WrapperCsvWriter {

	private FileWriter fw;
	private boolean isFirstIteration;

	public WrapperCsvWriter(String outputFile) {
		this.isFirstIteration = false;
		try {
			this.fw = new FileWriter(new File(outputFile));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @param output is the first output that is used to complete the csv header
	 */
	private void writeCsvHeader(IWrapperOutput output){
		StringBuffer line = new StringBuffer();
		for( Field f : output.getPrintableFields() ) {
			String fieldName = f.getName();
			line.append(fieldName + ";");
		}
		try {
			fw.write(line.toString()+"\n");
		} catch (IOException e) {
			e.printStackTrace();
		}
		this.isFirstIteration = false;
	}
	
	/**
	 * Prints the current output data in the output csv
	 * @param output is the output to be printed in the csv file
	 */
	public void writeInFile(IWrapperOutput output){
		try{
			if (isFirstIteration){
				writeCsvHeader(output);
			}
			StringBuffer line = new StringBuffer();
			Field[] printableFields = output.getPrintableFields();
			for (Field f : printableFields) {
				Object attribValue = f.get(output);
				if (attribValue == null || attribValue.toString().isEmpty()){
					line.append(" ;");
				}
				else {
					if (attribValue.toString().contains(";")){
						line.append("\"" + attribValue.toString().replaceAll("\"", "\"\"") + "\";");
					}
					else {
						line.append(attribValue.toString() + ";");
					}
				}
			}
			fw.write(line.toString()+"\n");
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void closeFile(){
		try {
			this.fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
